/* eslint-disable @typescript-eslint/no-explicit-any */
import type { ResponseError, RequestOptionsInit } from 'umi-request';
import { extend } from 'umi-request';
import { message } from 'antd';

/* 异常处理 */
const errorHandler = function (error: ResponseError) {
  console.log('errorHandler:', error);
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    message.error('服务器异常');
    console.error(error.response.status, error.request);
  } else {
    // The request was made but no response was received or error occurs when setting up the request.
    console.error('Request error:', error.message);
  }
  throw error;
};

const request = extend({
  // 为每个请求添加前缀
  // prefix: '/api',
  errorHandler,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 登录拦截
request.interceptors.response.use(async (response, options) => {
  const res = await response.clone().json();
  const { code, data } = res;
  if (res && code === 501 && data.loginPageUrl) {
    setTimeout(() => {
      window.location.href = `${data.loginPageUrl}${encodeURIComponent(
        `${location.origin}/usercenter-admin-web/`,
      )}`;
    }, 500);
  }
  return response;
});

/* 处理data */
const handleResponseData = <T>(data: T) => data;

const get = <T = any>(
  url: string,
  params?: Record<string, number | string | boolean> | URLSearchParams,
  options?: RequestOptionsInit,
) => request.get<T>(url, { ...options, params }).then(handleResponseData);

const post = <T = any>(url: string, data?: Record<string, any>, options?: RequestOptionsInit) =>
  request.post<T>(url, { ...options, data }).then(handleResponseData);

const put = <T = any>(url: string, data?: Record<string, any>, options?: RequestOptionsInit) =>
  request.put<T>(url, { ...options, data }).then(handleResponseData);

const del = <T = any>(url: string, data?: Record<string, any>, options?: RequestOptionsInit) =>
  request.delete<T>(url, { ...options, data }).then(handleResponseData);

const uploadLogs = <T = any>(url: string, data?: any, options?: RequestOptionsInit) =>
  window.fetch(url, { method: 'post', body: data }).then((response) => {
    if (response?.status === 200) return response.json();
    if (response?.status === 413) {
      return {
        code: -1,
        message: '上传文件过大',
      };
    }
    return {
      code: -1,
      message: '上传失败',
    };
  });

/**
 * // How to upload file?
 * const formData = new FormData();
 * formData.append('file', file);
 * fetch('/api/v1/some/api', { method: 'POST', body: formData });
 */

// 导出你所需要使用的方法
export { request, get, post, put, del, uploadLogs };
